<!-- 服务期消息类型 -->
<template>
  <div class="temp-container">
    <!-- 消息名称 -->
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span class="col_title">消息名称</span>
      </div>
      <el-form
        :model="serviceForm"
        :rules="serviceRules"
        ref="serviceForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="消息名称" prop="name">
          <el-input
            style="width:50%;margin-left:100px"
            v-model="serviceForm.name"
            show-word-limit
            maxlength="32"
          ></el-input>
        </el-form-item>
      </el-form>
    </el-card>
    <!-- 选择订单 -->
    <el-card
      class="box-card"
      v-loading="loading"
      element-loading-text="正在计算选择的订单量"
      element-loading-spinner="el-icon-loading"
      element-loading-background="rgba(255,255,255,0)"
    >
      <div slot="header" class="clearfix">
        <span class="col_title">选择订单</span>
      </div>
      <el-form
        :model="serviceForm.configData"
        :rules="orderRules"
        ref="orderForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="选择订单" prop="serviceExpiresType">
          <el-radio-group
            v-model="serviceForm.configData.serviceExpiresType"
            style="width:50%;margin-left:100px"
          >
            <el-radio label="ALL">所有订单</el-radio>
            <el-radio label="SPECIFIED_TIME">指定服务期到期订单</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          prop="startTime"
          v-if="serviceForm.configData.serviceExpiresType == 'SPECIFIED_TIME'"
        >
          <div class="serviceTime">
            到期时间范围
            <el-date-picker
              style="width:400px;margin-left:20px"
              v-model="serviceTime"
              size="small"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="yyyy-MM-dd"
              @change="handleDateChange"
            >
            </el-date-picker>
          </div>
        </el-form-item>
        <el-form-item
          v-show="serviceForm.configData.serviceExpiresType == 'ALL'"
        >
          <div class="view-order_btn" @click="viewsOrder()">
            查看订单
          </div>
        </el-form-item>
        <el-form-item
          v-show="serviceForm.configData.serviceExpiresType == 'SPECIFIED_TIME'"
        >
          <div class="view-order_btn" @click="viewsOrder('SPECIFIED_TIME')">
            查看订单
          </div>
        </el-form-item>
        <el-form-item label="通知条件" prop="daysBeforeExpiration">
          <div class="form-box">
            <span style="margin-right: 30px">服务期到期前</span>
            <el-checkbox-group
              v-model="serviceForm.configData.daysBeforeExpiration"
            >
              <el-checkbox :label="180">180天</el-checkbox>
              <el-checkbox :label="120">120天</el-checkbox>
              <el-checkbox :label="60">60天</el-checkbox>
              <el-checkbox :label="3">3天</el-checkbox>
            </el-checkbox-group>
          </div>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 用户通知 -->
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span class="col_title">通知用户</span>
      </div>
      <el-form
        :model="serviceForm.configData"
        label-width="100px"
        class="demo-ruleForm"
        v-loading="loadingPost"
        element-loading-text="正在计算选择的人数"
        element-loading-spinner="el-icon-loading"
        element-loading-background="rgba(255,255,255,0)"
      >
        <el-form-item label="通知用户" prop="userType">
          <div class="notice-wrap">
            <el-radio-group v-model="serviceForm.configData.userType">
              <el-radio label="STUDENT">
                学员
                <span class="notice-btn" @click="viewsNum('isview')">
                  查看人数</span
                >
              </el-radio>
              <el-radio label="CONSULTANT">顾问</el-radio>
            </el-radio-group>
          </div>
          <div class="notice-wrap">
            说明：消息发送时会做发送号码和发送内容的去重，最终发送人数以详情页的【发送数量】为准；
          </div>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 发送渠道 -->
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span class="col_title">发送渠道</span>
      </div>
      <!-- 短信渠道 -->
      <el-form
        :model="channelsList.sms"
        :rules="smsRules"
        ref="smsForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <!-- 渠道短信 -->
        <el-form-item label="选择渠道" prop="sms">
          <div class="channel-wrap">
            <el-checkbox
              class="channel-checkbox"
              label="SMS"
              v-model="smsChecked"
              @change="smsCheckedChange"
              >短信</el-checkbox
            >
            <p v-if="smsChecked">
              注意：短信是收费项目，请谨慎选择!
            </p>
          </div>
        </el-form-item>
        <el-form-item prop="content">
          <div class="channel-content">
            <div slot="header" class="clearfix">
              <span>编辑内容</span>
            </div>
            <div>
              <el-input
                type="textarea"
                :rows="10"
                placeholder="请输入通知内容"
                v-model="channelsList.sms.content"
                maxlength="195"
                show-word-limit
              >
              </el-input>
            </div>
          </div>
        </el-form-item>
        <el-form-item>
          <div class="link-content">
            <span class="short-link">短链</span>
            <el-input
              v-model="smsLink"
              placeholder="请输入内容"
              style="flex: 1"
            ></el-input>
            <span @click="changeChain('sms')" class="row_center short-link-btn"
              >转链并插入</span
            >
          </div>
        </el-form-item>
        <el-form-item
          v-show="this.serviceForm.configData.userType == 'CONSULTANT'"
        >
          <div class="channel-content">
            <span class="content-tip">追加学员信息</span>
            <el-radio-group
              v-model="
                serviceForm.configData.messageContentAppendConfigs.sms
                  .whetherAppend
              "
            >
              <el-radio :label="true">是</el-radio>
              <el-radio :label="false">否</el-radio>
            </el-radio-group>
          </div>
        </el-form-item>
        <el-form-item
          prop="studentInfo"
          v-show="this.serviceForm.configData.userType == 'CONSULTANT'"
          v-if="
            serviceForm.configData.messageContentAppendConfigs.sms.whetherAppend
          "
        >
          <div class="channel-content">
            <span class="content-tip">学员信息</span>
            <el-checkbox
              v-model="
                serviceForm.configData.messageContentAppendConfigs.sms
                  .appendStudentName
              "
              @change="checkedStudentName"
              :disabled="disabledSMS"
              >姓名</el-checkbox
            >
            <el-checkbox
              :disabled="disabledSMS"
              v-model="
                serviceForm.configData.messageContentAppendConfigs.sms
                  .appendStudentDpNumber
              "
              @change="checkedStudentDpNumber"
              >大鹏号</el-checkbox
            >
          </div>
        </el-form-item>
      </el-form>
      <!-- 钉钉渠道 -->
      <el-form
        v-show="serviceForm.configData.userType === 'CONSULTANT'"
        :model="channelsList.dingtalk"
        :rules="dingtalkRules"
        ref="dingtalkForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item prop="dingtalk">
          <div class="channel-wrap">
            <el-checkbox
              class="channel-checkbox"
              label="DINGTALK"
              v-model="dingtalkChecked"
              @change="dingCheckedChange"
              >钉钉</el-checkbox
            >
          </div>
        </el-form-item>
        <el-form-item prop="title">
          <div class="channel-content">
            <el-input
              type="text"
              placeholder="请输入通知标题"
              v-model="channelsList.dingtalk.title"
              show-word-limit
              maxlength="32"
            >
            </el-input>
          </div>
        </el-form-item>
        <el-form-item prop="content">
          <div class="channel-content">
            <div slot="header" class="clearfix">
              <span>编辑内容</span>
            </div>
            <div>
              <el-input
                type="textarea"
                :rows="10"
                placeholder="请输入通知内容"
                v-model="channelsList.dingtalk.content"
                maxlength="195"
                show-word-limit
              >
              </el-input>
            </div>
          </div>
        </el-form-item>
        <el-form-item>
          <div class="link-content">
            <span class="short-link">短链</span>
            <el-input
              v-model="dingShortLink"
              placeholder="请输入内容"
              style="flex: 1"
            ></el-input>
            <span @click="changeChain('ding')" class="row_center short-link-btn"
              >转链并插入</span
            >
          </div>
        </el-form-item>
        <el-form-item>
          <div class="channel-content">
            <span class="content-tip">追加学员信息</span>
            <el-radio-group
              v-model="
                serviceForm.configData.messageContentAppendConfigs.dingtalk
                  .whetherAppend
              "
            >
              <el-radio :label="true">是</el-radio>
              <el-radio :label="false">否</el-radio>
            </el-radio-group>
          </div>
        </el-form-item>
        <el-form-item
          prop="dingStudentName"
          v-if="
            serviceForm.configData.messageContentAppendConfigs.dingtalk
              .whetherAppend == true
          "
        >
          <div class="channel-content">
            <span class="content-tip">学员信息</span>

            <el-checkbox
              @change="DingcheckedStudentName"
              v-model="
                serviceForm.configData.messageContentAppendConfigs.dingtalk
                  .appendStudentName
              "
              :disabled="disabledDing"
              >姓名</el-checkbox
            >
            <el-checkbox
              @change="dingStudentDpNumber"
              :disabled="disabledDing"
              v-model="
                serviceForm.configData.messageContentAppendConfigs.dingtalk
                  .appendStudentDpNumber
              "
              >大鹏号</el-checkbox
            >
          </div>
        </el-form-item>
      </el-form>
      <!-- 渠道站内信 -->
      <el-form
        v-show="serviceForm.configData.userType === 'STUDENT'"
        :model="channelsList.notice"
        :rules="noticeRules"
        ref="noticeForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item prop="notice">
          <div class="channel-wrap">
            <el-checkbox
              class="channel-checkbox"
              label="NOTICE"
              v-model="noticeChecked"
              @change="noticeCheckedChange"
              >站内信</el-checkbox
            >
          </div>
        </el-form-item>
        <el-form-item prop="title">
          <div class="channel-content">
            <el-input
              type="text"
              placeholder="请输入通知标题"
              v-model="channelsList.notice.title"
              maxlength="32"
              show-word-limit
            >
            </el-input>
          </div>
        </el-form-item>
        <el-form-item prop="content">
          <div class="channel-content">
            <div slot="header" class="clearfix">
              <span>编辑内容</span>
            </div>
            <div>
              <el-input
                type="textarea"
                :rows="10"
                placeholder="请输入通知内容"
                v-model="channelsList.notice.content"
                maxlength="300"
                show-word-limit
              >
              </el-input>
            </div>
          </div>
        </el-form-item>
        <el-form-item prop="link">
          <div class="link-content">
            <span class="short-link">跳转链接</span>
            <el-input
              style="flex: 1"
              v-model="channelsList.notice.link"
            ></el-input>
          </div>
        </el-form-item>
      </el-form>
      <!-- 渠道推送 -->
      <el-form
        v-show="serviceForm.configData.userType === 'STUDENT'"
        :model="channelsList.push"
        :rules="pushRules"
        ref="pushForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item prop="push">
          <div class="channel-wrap">
            <el-checkbox
              class="channel-checkbox"
              label="PUSH"
              v-model="pushChecked"
              @change="pushCheckedChange"
              >推送</el-checkbox
            >
            <p v-if="pushChecked">
              注意：推送是收费项目，请谨慎选择!
            </p>
          </div>
        </el-form-item>
        <el-form-item prop="title">
          <div class="channel-content">
            <el-input
              type="text"
              placeholder="请输入通知标题"
              v-model="channelsList.push.title"
              show-word-limit
              maxlength="30"
            >
            </el-input>
          </div>
        </el-form-item>
        <el-form-item prop="content">
          <div class="channel-content">
            <div slot="header" class="clearfix">
              <span>编辑内容</span>
            </div>
            <div>
              <el-input
                type="textarea"
                :rows="10"
                placeholder="请输入通知内容"
                v-model="channelsList.push.content"
                maxlength="128"
                show-word-limit
              >
              </el-input>
            </div>
          </div>
        </el-form-item>
        <el-form-item prop="link">
          <div class="push-content">
            <el-row style="margin-left:100px;">
              <el-col :span="2">
                <span>后续动作</span>
              </el-col>

              <el-col :span="5">
                <el-select
                  v-model="channelsList.push.pushType"
                  @change="pushTypeChange"
                >
                  <el-option label="启动应用" value="OPEN_APP"
                    >启动应用</el-option
                  >
                  <el-option label="打开第三方链接" value="THIRD_LINK"
                    >打开第三方链接</el-option
                  >
                  <el-option label="跳转应用内特定页面" value="OPEN_APP_LINK"
                    >跳转应用内特定页面</el-option
                  >
                  <el-option label="跳转到小程序" value="OPEN_WECHAT_APPLET"
                    >跳转到小程序</el-option
                  >
                </el-select>
              </el-col>

              <el-col
                :span="5"
                v-if="channelsList.push.pushType === 'OPEN_APP_LINK'"
              >
                <el-select
                  v-model="channelsList.push.appJumpPage"
                  placeholder="请选择跳转页面"
                  style="width:300px;margin-left:5px;"
                >
                  <el-option
                    v-for="item in appJumpOption"
                    :key="item.dictLabel"
                    :label="item.dictValue"
                    :value="item.dictLabel"
                    >{{ item.dictValue }}</el-option
                  >
                </el-select>
              </el-col>

              <el-col
                :span="5"
                v-if="channelsList.push.pushType === 'OPEN_APP_LINK'"
              >
                <el-input
                  v-model.trim="channelsList.push.link"
                  placeholder="请输入页面地址"
                  style="width:80%;margin-left:30px;"
                >
                </el-input>
              </el-col>

              <el-col
                :span="5"
                v-if="channelsList.push.pushType === 'OPEN_WECHAT_APPLET'"
              >
                <el-input
                  v-model.trim="channelsList.push.link"
                  placeholder="请输入小程序ID"
                  style="width:80%;margin-left:5px;"
                >
                </el-input>
              </el-col>

              <el-col
                :span="8"
                v-if="channelsList.push.pushType === 'THIRD_LINK'"
              >
                <el-input
                  v-model.trim="channelsList.push.link"
                  placeholder="请输入跳转链接"
                  style="width:80%;margin-left:5px;"
                >
                </el-input>
              </el-col>
            </el-row>
          </div>
        </el-form-item>
      </el-form>
      <!-- 渠道弹屏 -->
      <el-form
        v-show="serviceForm.configData.userType === 'STUDENT'"
        :model="channelsList.playscreen"
        :rules="playscreenRules"
        ref="playscreenForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item prop="playscreen">
          <div class="channel-wrap">
            <el-checkbox
              class="channel-checkbox"
              label="PLAYSCREEN"
              v-model="playscreenChecked"
              @change="playscreenCheckedChange"
            >
              弹屏
            </el-checkbox>
          </div>
        </el-form-item>

        <el-form-item prop="bombScreenType">
          <div class="playscreen-wrap">
            <span style="margin-right:20px;">显示端口</span>
            <el-radio-group v-model="channelsList.playscreen.bombScreenType">
              <el-radio label="APP">APP</el-radio>
              <el-radio label="PC">PC</el-radio>
              <el-radio label="H5">H5</el-radio>
            </el-radio-group>
          </div>
        </el-form-item>

        <el-form-item prop="bombScreenImage">
          <div class="playscreen-wrap">
            <span style="margin-right:20px;float:left;">弹屏图片</span>
            <uploadSingImg
              :imgUrl="channelsList.playscreen.bombScreenImage"
              accept=".jpg,.png,.gif"
              :maxSize="5"
              @getImgUrl="getImgUrl"
              :showDeleteIcon="true"
            ></uploadSingImg>
            <div style="margin-left:80px;">
              建议尺寸要求：330*330，JPG、GIF、PNG格式
            </div>
          </div>
        </el-form-item>

        <el-form-item prop="link">
          <div class="link-content">
            <span class="short-link">跳转链接</span>
            <el-input
              style="flex: 1"
              v-model="channelsList.playscreen.link"
              placeholder="请输入跳转链接"
            ></el-input>
          </div>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 发送时间 -->
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span class="col_title">发送时间</span>
      </div>
      <el-form
        :model="serviceForm.configData"
        :rules="timeRules"
        ref="timeForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <div
          class="form-box"
          style="width:50%;display:flex;justify-content:space-around;align-items:center"
        >
          <el-form-item prop="hourTime" label="提醒当天">
            <el-select v-model="hour" placeholder="请选择">
              <el-option
                v-for="item in hourList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <span style="height:100%;" class="position_top">时</span>
          <el-form-item prop="minutesTime">
            <el-select v-model="minutes" placeholder="请选择">
              <el-option
                v-for="item in minutesList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <span style="height:100%;" class="position_top">分</span>
        </div>
      </el-form>

      <el-row justify="center" type="flex" style="margin-top:50px">
        <el-col :span="4">
          <el-button type="success" @click="saveService">保存</el-button>
          <el-button type="success" plain @click="cancel">取消</el-button>
        </el-col>
      </el-row>
    </el-card>
    <!-- 显示选择订单数量 -->
    <selectedNumDialog :formLimit="formLimit"></selectedNumDialog>
  </div>
</template>

<script>
import { sysNormalDisable } from '@utils/dictionariesFunc'
import selectedNumDialog from '@/components/messageManagement/template/selectedNumDialog.vue'
import {
  searchStudentNum,
  serveList,
  createService,
  serverTemplateData,
  compileService,
  turnChain
} from '@/api/notice'
import { clearTagMixins } from '@/mixins/clearTag.js'
import uploadSingImg from '@common/uploadSingImg' // 上传单个图片公共组件
export default {
  name: 'serverTemplate',
  mixins: [clearTagMixins],
  data() {
    var validateDingStudentInfo = (rule, value, callback) => {
      if (
        this.serviceForm.configData.messageContentAppendConfigs.dingtalk
          .whetherAppend &&
        !this.serviceForm.configData.messageContentAppendConfigs.dingtalk
          .appendStudentName &&
        !this.serviceForm.configData.messageContentAppendConfigs.dingtalk
          .appendStudentDpNumber &&
        this.smsChecked
      ) {
        callback(new Error('请至少选择一个学员信息'))
      } else {
        callback()
      }
    }
    var validateSmsStudentInfo = (rule, value, callback) => {
      if (
        this.serviceForm.configData.messageContentAppendConfigs.sms
          .whetherAppend &&
        !this.serviceForm.configData.messageContentAppendConfigs.sms
          .appendStudentName &&
        !this.serviceForm.configData.messageContentAppendConfigs.sms
          .appendStudentDpNumber &&
        this.smsChecked
      ) {
        callback(new Error('请至少选择一个学员信息'))
      } else {
        callback()
      }
    }
    // 校验指定服务期到期时间
    var validateStartTime = (rule, value, callback) => {
      if (this.serviceForm.configData.serviceExpiresType == 'SPECIFIED_TIME') {
        if (value !== '') {
          callback()
        } else {
          callback(new Error('请选择到期时间范围'))
        }
      } else {
        callback()
      }
    }
    // 校验短信渠道
    var validateSmsChannels = (rule, value, callback) => {
      if (
        this.smsChecked ||
        this.dingtalkChecked ||
        this.noticeChecked ||
        this.pushChecked ||
        this.playscreenChecked
      ) {
        callback()
      } else {
        callback(new Error('请选择渠道'))
      }
    }
    // 校验短信内容渠道
    var validateSmsContent = (rule, value, callback) => {
      if (this.smsChecked) {
        if (value === '') {
          callback(new Error('请输入通知内容'))
        } else if (value.length > 195) {
          callback(new Error('输入内容超过最大长度限制'))
        } else {
          callback()
        }
      } else {
        callback()
      }
    }
    var validataDdingTitle = (rule, value, callback) => {
      if (this.dingtalkChecked) {
        if (value == '') {
          callback(new Error('标题不能为空'))
        } else {
          callback()
        }
      } else {
        callback()
      }
    }
    // 校验钉钉渠道
    var validateDingChannels = (rule, value, callback) => {
      if (
        this.smsChecked ||
        this.dingtalkChecked ||
        this.noticeChecked ||
        this.pushChecked ||
        this.playscreenChecked
      ) {
        callback()
      } else {
        callback(new Error('请选择渠道'))
      }
    }
    // 校验短信内容渠道
    var validateDingContent = (rule, value, callback) => {
      if (this.dingtalkChecked) {
        if (value === '') {
          callback(new Error('请输入通知内容'))
        } else if (value.length > 195) {
          callback(new Error('输入内容超过最大长度限制'))
        } else {
          callback()
        }
      } else {
        callback()
      }
    }
    // 校验站内信渠道
    var validateNoticeChannels = (rule, value, callback) => {
      if (
        this.smsChecked ||
        this.dingtalkChecked ||
        this.noticeChecked ||
        this.pushChecked ||
        this.playscreenChecked
      ) {
        callback()
      } else {
        callback(new Error('请选择渠道'))
      }
    }
    // 校验站内信渠道内容
    var validateNoticeContent = (rule, value, callback) => {
      if (this.noticeChecked) {
        if (value === '') {
          callback(new Error('请输入站内信内容'))
        } else if (value.length > 195) {
          callback(new Error('输入内容超过最大长度限制'))
        } else {
          callback()
        }
      } else {
        callback()
      }
    }
    // 校验站内信渠道标题
    var validateNoticeTitle = (rule, value, callback) => {
      if (this.noticeChecked) {
        if (value === '') {
          callback(new Error('请输入站内信标题'))
        } else {
          callback()
        }
      } else {
        callback()
      }
    }
    // 校验推送渠道
    var validatePushChannels = (rule, value, callback) => {
      if (
        this.smsChecked ||
        this.dingtalkChecked ||
        this.noticeChecked ||
        this.pushChecked ||
        this.playscreenChecked
      ) {
        callback()
      } else {
        callback(new Error('请选择渠道'))
      }
    }
    // 校验推送跳转链接
    var validaePushLink = (rule, value, callback) => {
      if (this.pushChecked) {
        if (
          this.channelsList.push.pushType == 'THIRD_LINK' &&
          this.channelsList.push.link == ''
        ) {
          callback(new Error('请输入跳转链接'))
        } else {
          callback()
        }
      } else {
        callback()
      }
    }
    // 检验url的正确性
    var validaePatternLink = (rule, value, callback) => {
      if (this.pushChecked) {
        let oRegUrl = new RegExp()
        oRegUrl.compile(
          '(https?|ftp|file)://[-A-Za-z0-9+&@#/%?=~_|!:,.;]+[-A-Za-z0-9+&@#/%=~_|]'
        )
        if (
          this.channelsList.push.pushType == 'THIRD_LINK' &&
          !oRegUrl.test(this.channelsList.push.link)
        ) {
          callback(new Error('请输入正确的详情链接url'))
        } else {
          callback()
        }
      } else {
        callback()
      }
    }
    // 校验推送渠道内容
    var validatePushContent = (rule, value, callback) => {
      if (this.pushChecked) {
        if (value === '') {
          callback(new Error('请输入推送内容'))
        } else if (value.length > 128) {
          callback(new Error('输入内容超过最大长度限制'))
        } else {
          callback()
        }
      } else {
        callback()
      }
    }
    // 选择时间中的小时校验
    var validateHourTest = (rule, value, callback) => {
      if (!this.hour) {
        callback(new Error('请正确选择小时'))
      } else {
        callback()
      }
    }
    var validateminutesTest = (rule, value, callback) => {
      if (!this.minutes) {
        callback(new Error('请正确选择分钟'))
      } else {
        callback()
      }
    }
    // 校验推送渠道标题
    var validatePushTitle = (rule, value, callback) => {
      if (this.pushChecked) {
        if (value === '') {
          callback(new Error('请输入推送标题'))
        } else {
          callback()
        }
      } else {
        callback()
      }
    }
    // 检验弹屏
    var validatePlayscreenChannels = (rule, value, callback) => {
      if (
        this.smsChecked ||
        this.dingtalkChecked ||
        this.noticeChecked ||
        this.pushChecked ||
        this.playscreenChecked
      ) {
        callback()
      } else {
        callback(new Error('请选择渠道'))
      }
    }
    // 校验弹屏端口
    var validateScreenPort = (rule, value, callback) => {
      if (this.playscreenChecked) {
        if (value === '') {
          callback(new Error('请选择端口'))
        } else {
          callback()
        }
      } else {
        callback()
      }
    }
    // 校验弹屏图片
    var validateScreenPhoto = (rule, value, callback) => {
      if (this.playscreenChecked) {
        if (value === '') {
          callback(new Error('请选择弹屏图片'))
        } else {
          callback()
        }
      } else {
        callback()
      }
    }

    return {
      hour: '',
      hourList: [],
      minutes: '',
      minutesList: [],
      disabledSMS: false,
      disabledDing: false,
      studentCount: 100,
      dingShortLink: '',
      // 服务期表单
      serviceForm: {
        name: '', // 消息名称
        messageTemplateAlias: 'PERIOD_OF_SERVICE_MESSAGE_TEMPLATE', // 消息类型
        configData: {
          serviceExpiresType: '', // 订单(到期)类型
          daysBeforeExpiration: [], // 通知条件
          userType: 'STUDENT', // 通知用户类型
          runTime: '', // 发送时间
          startTime: '', // 指定服务期开始日期
          endTime: '', // 指定服务期结束日期
          messageContentAppendConfigs: {
            dingtalk: {
              appendStudentDpNumber: false,
              appendStudentName: false,
              whetherAppend: true
            },
            sms: {
              appendStudentDpNumber: false,
              appendStudentName: false,
              whetherAppend: true
            }
          }
        },
        // 渠道列表
        messageChannels: []
      },
      serviceTime: [],
      smsChecked: false,
      smsLink: '', // 短信短链接
      dingtalkChecked: false,
      noticeChecked: false,
      pushChecked: false,
      playscreenChecked: false,
      appJumpOption: [],
      channelsList: {
        // 短信(转换链接后将短链前后加空格追加到内容后面)
        sms: {
          content: '',
          type: 'SMS'
        },
        // 钉钉消息
        dingtalk: {
          title: '',
          content: '',
          type: 'DINGTALK'
        },
        // 站内信
        notice: {
          title: '',
          content: '',
          link: '',
          type: 'NOTICE'
        },
        // 推送
        push: {
          title: '',
          content: '',
          pushType: 'OPEN_APP',
          link: '',
          type: 'PUSH',
          appJumpPage: null
        },
        // 弹屏
        playscreen: {
          bombScreenType: '',
          bombScreenImage: '',
          link: '',
          type: 'BOMB_SCREEN'
        }
      },
      // 服务期规则
      serviceRules: {
        name: [
          { required: true, message: '请输入消息名称', trigger: 'blur' },
          { min: 1, max: 32, message: '长度不超过32字符', trigger: 'blur' }
        ]
      },
      // 订单校验
      orderRules: {
        serviceExpiresType: [
          { required: true, message: '请选择订单类型', trigger: 'change' }
        ],
        startTime: [{ validator: validateStartTime, trigger: 'change' }],
        daysBeforeExpiration: [
          {
            type: 'array',
            required: true,
            message: '请至少选择一个通知条件',
            trigger: 'change'
          }
        ]
      },
      // 发送时间校验
      timeRules: {
        runTime: [
          {
            required: true,
            message: '请选择发送时间',
            trigger: 'change'
          }
        ],
        hourTime: [
          { validator: validateHourTest, targe: 'change', required: true }
        ],
        minutesTime: [
          { validator: validateminutesTest, target: 'change', required: true }
        ]
      },
      // 发送短信渠道校验
      smsRules: {
        sms: [
          { required: true, validator: validateSmsChannels, trigger: 'change' }
        ],
        content: [{ validator: validateSmsContent, trigger: 'blur' }],
        studentInfo: [{ validator: validateSmsStudentInfo, trigger: 'blur' }]
      },
      // 发送钉钉渠道校验
      dingtalkRules: {
        title: [
          { min: 1, max: 32, message: '标题最长32个字符', trigger: 'blur' },
          { validator: validataDdingTitle, trigger: 'change' }
        ],
        dingStudentName: [{ validator: validateDingStudentInfo }],
        dingtalk: [{ validator: validateDingChannels, trigger: 'change' }],
        content: [{ validator: validateDingContent, trigger: 'blur' }]
      },
      // 发送站内渠道校验
      noticeRules: {
        link: {
          pattern:
            '(https?|ftp|file)://[-A-Za-z0-9+&@#/%?=~_|!:,.;]+[-A-Za-z0-9+&@#/%=~_|]',
          message: '请输入正确的详情链接url',
          trigger: 'blur'
        },
        title: [
          { min: 1, max: 32, message: '标题最长32个字符', trigger: 'change' },
          { validator: validateNoticeTitle, trigger: 'change' }
        ],
        notice: [{ validator: validateNoticeChannels, trigger: 'change' }],
        content: [{ validator: validateNoticeContent, trigger: 'blur' }]
      },
      // 发送站内渠道校验
      pushRules: {
        title: [
          { min: 1, max: 32, message: '标题最长32个字符', trigger: 'change' },
          { validator: validatePushTitle, trigger: 'change' }
        ],
        push: [{ validator: validatePushChannels, trigger: 'change' }],
        content: [{ validator: validatePushContent, trigger: 'change' }],
        link: [
          { validator: validaePushLink, trigger: 'change' },
          { validator: validaePatternLink, trigger: 'blur' }
        ]
      },
      // 发送站内弹屏校验
      playscreenRules: {
        playscreen: [
          { validator: validatePlayscreenChannels, trigger: 'change' }
        ],
        bombScreenType: [{ validator: validateScreenPort, trigger: 'change' }],
        bombScreenImage: [
          { validator: validateScreenPhoto, trigger: 'change' }
        ],
        link: {
          pattern:
            '(https?|ftp|file)://[-A-Za-z0-9+&@#/%?=~_|!:,.;]+[-A-Za-z0-9+&@#/%=~_|]',
          message: '请输入正确的详情链接url',
          trigger: 'blur'
        }
      },
      loading: false,
      loadingPost: false,
      formLimit: {
        visible: false,
        value: ''
      },
      pushCheck: false
    }
  },
  components: {
    selectedNumDialog,
    uploadSingImg
  },
  created() {
    var i = 0
    var j = 0
    for (i = 0; i <= 23; i++) {
      let obj = {
        value: i,
        label: i
      }
      if (i < 10) {
        obj.value = '0' + i
        obj.label = '0' + i
      }
      this.hourList.push(obj)
    }
    for (j = 0; j <= 59; j++) {
      let obj = {
        value: j,
        label: j
      }
      if (j < 10) {
        obj.value = '0' + j
        obj.label = '0' + j
      }
      this.minutesList.push(obj)
    }
    this.viewsNum()
    if (this.$route.query.id) {
      serverTemplateData(
        this.$route.query.id,
        (res) => {
          this.serviceForm = res
          this.messageChannelsToChannelsList()
          this.dueDateToserviceTime(
            res.configData.startTime,
            res.configData.endTime
          )
          let a = res.configData.runTime.indexOf(':')
          this.hour = res.configData.runTime.substring(0, a)
          let b = res.configData.runTime.length
          this.minutes = res.configData.runTime.substring(a + 1, b)
        },
        (err) => {}
      )
    }
  },

  async mounted() {
    let data = await sysNormalDisable('app_jump_page')
    this.appJumpOption = this.appJumpOption.concat(data)
  },

  methods: {
    async pushTypeChange(val) {
      this.$refs['pushForm'].validateField('link', (errMsg) => {})
      if (val === 'OPEN_APP_LINK') {
        this.channelsList.push.link = ''
        this.channelsList.push.appJumpPage = null
        this.appJumpOption = []
        let data = await sysNormalDisable('app_jump_page')
        this.appJumpOption = this.appJumpOption.concat(data)
      } else {
        this.channelsList.push.link = ''
        this.appJumpOption = []
      }
    },
    dingStudentDpNumber(val) {
      this.serviceForm.configData.messageContentAppendConfigs.dingtalk.appendStudentDpNumber = val
      this.$refs['dingtalkForm'].validateField(
        'dingStudentName',
        (errMsg) => {}
      )
    },
    DingcheckedStudentName(val) {
      this.serviceForm.configData.messageContentAppendConfigs.dingtalk.appendStudentName = val
      this.$refs['dingtalkForm'].validateField(
        'dingStudentName',
        (errMsg) => {}
      )
    },
    checkedStudentDpNumber(val) {
      this.serviceForm.configData.messageContentAppendConfigs.sms.appendStudentDpNumber = val
      this.$refs['smsForm'].validateField('studentInfo', (errMsg) => {})
    },
    checkedStudentName(val) {
      this.serviceForm.configData.messageContentAppendConfigs.sms.appendStudentName = val
      this.$refs['smsForm'].validateField('studentInfo', (errMsg) => {})
    },
    open(val) {
      let money =
        Math.ceil(this.channelsList.sms.content.length / 67) *
        0.038 *
        this.studentCount
      let changeMoney = money.toFixed(2)
      this.$confirm(
        `您选择的短信消息预计消耗费用${changeMoney}元，, 确定发送短信吗?`,
        '费用提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          center: true
        }
      )
        .then(() => {
          if (val == 'compile') {
            this.compile()
          } else {
            this.saveSon()
          }
        })
        .catch(() => {
          return false
        })
    },
    changeChain(val) {
      if (val == 'sms') {
        let params = {}
        params.longURL = this.smsLink
        turnChain(
          params,
          (res) => {
            if (
              this.channelsList.sms.content.length +
                ` ${res.shortURL} `.length >
              195
            ) {
              this.$message({
                message: '短信编辑内容字数不能超过195',
                type: 'warn'
              })
              return false
            }
            this.channelsList.sms.content =
              this.channelsList.sms.content + ` ${res.shortURL} `
            this.smsLink = ''
          },
          (err) => {
            this.$message({
              message: err.message,
              type: 'warn'
            })
          }
        )
      } else {
        let params = {}
        params.longURL = this.dingShortLink
        turnChain(
          params,
          (res) => {
            if (
              this.channelsList.dingtalk.content.length +
                ` ${res.shortURL} `.length >
              195
            ) {
              this.$message({
                message: '钉钉编辑内容字数不能超过195',
                type: 'warn'
              })
              return false
            }
            this.channelsList.dingtalk.content =
              this.channelsList.dingtalk.content + ` ${res.shortURL} `
            this.dingShortLink = ''
          },
          (err) => {
            this.$message({
              message: err.message,
              type: 'warn'
            })
          }
        )
      }
    },
    cancel() {
      this.clearTag()
    },
    compile() {
      let id = this.$route.query.id
      let params = Object.assign({}, this.serviceForm)
      compileService(
        id,
        params,
        (res) => {
          this.$message({
            message: '编辑成功',
            type: 'success'
          })
          _this.serviceForm.messageChannels = []
          this.clearTag()
        },
        (err) => {
          this.$message({
            message: err.message,
            type: 'warn'
          })
          _this.serviceForm.messageChannels = []
          return false
        }
      )
    },
    saveSon() {
      let _this = this
      let params = Object.assign({}, this.serviceForm)
      createService(
        params,
        (res) => {
          this.$message({
            message: '创建成功',
            type: 'success'
          })
          this.clearTag()
          _this.serviceForm.messageChannels = []
        },
        (err) => {
          this.$message({
            message: err.message,
            type: 'warn'
          })
          _this.serviceForm.messageChannels = []
          return false
        }
      )
    },
    saveService() {
      let serviceForm = false
      let orderForm = false
      let channelsForm = false
      let timeForm = false
      this.$refs['serviceForm'].validate((valid) => {
        if (valid) {
          serviceForm = true
        }
      })
      this.$refs['orderForm'].validate((valid) => {
        if (valid) {
          orderForm = true
        }
      })
      this.$refs['timeForm'].validate((valid) => {
        if (valid) {
          timeForm = true
        }
      })
      // 判断通知用户类型 => 学员
      if (this.serviceForm.configData.userType === 'STUDENT') {
        if (
          !this.smsChecked &&
          !this.noticeChecked &&
          !this.pushChecked &&
          !this.playscreenChecked
        ) {
          this.$refs['smsForm'].validate((valid) => {
            if (!valid) {
              return false
            }
          })
          this.$refs['noticeForm'].validate((valid) => {
            if (!valid) {
              return false
            }
          })
          this.$refs['pushForm'].validate((valid) => {
            if (!valid) {
              return false
            }
          })
          this.$refs['playscreenForm'].validate((valid) => {
            if (!valid) {
              return false
            }
          })
        } else {
          channelsForm = true
        }
      }

      // 判断通知用户类型 => 顾问
      if (this.serviceForm.configData.userType === 'CONSULTANT') {
        if (!this.smsChecked && !this.dingtalkChecked) {
          this.$refs['smsForm'].validate((valid) => {
            if (!valid) {
              return false
            }
          })
          this.$refs['dingtalkForm'].validate((valid) => {
            if (!valid) {
              return false
            }
          })
        } else {
          channelsForm = true
        }
      }

      // 校验必选项
      if (!serviceForm || !orderForm || !timeForm || !channelsForm) {
        return false
      }

      // 端口与弹屏图片校验
      if (this.playscreenChecked) {
        const { bombScreenImage, bombScreenType } = this.channelsList.playscreen
        if (bombScreenImage === '' || bombScreenType === '') {
          return false
        }
      }

      this.channelsListToMessageChannels()
      this.serviceForm.configData.runTime = this.hour + ':' + this.minutes
      if (this.$route.query.id) {
        if (
          this.smsChecked &&
          this.serviceForm.configData.userType == 'STUDENT'
        ) {
          this.open('compile')
        } else {
          this.compile()
        }
      } else {
        if (
          this.smsChecked &&
          this.serviceForm.configData.userType == 'STUDENT'
        ) {
          this.open('saveSon')
        } else {
          this.saveSon()
        }
      }
    },

    // 查看人数 两个弹窗之一
    viewsNum(val) {
      var _this = this
      if (val) {
        this.loadingPost = true
      }
      let params = {}
      params.startTime = this.serviceTime[0]
      params.endTime = this.serviceTime[1]
      searchStudentNum(
        params,
        (res) => {
          _this.loadingPost = false
          if (val) {
            _this.formLimit.visible = true
          }
          _this.studentCount = res.total
          _this.formLimit.value = `您本次选择了${res.total}人`
        },
        (err) => {}
      )
    },

    viewsOrder(type = 'ALL') {
      const _this = this
      let params = {}
      if (type === 'SPECIFIED_TIME') {
        this.$refs['orderForm'].validateField('startTime', (errMsg) => {
          if (errMsg) {
            return false
          } else {
            const startTime = _this.serviceForm.configData.startTime
            const endTime = _this.serviceForm.configData.endTime
            _this.loading = true
            params = {
              startTime,
              endTime,
              type: 'EXPIREORDERS'
            }
            serveList(
              params,
              (res) => {
                _this.loading = false
                _this.formLimit.visible = true
                _this.formLimit.value = `您本次选择了${res.total}条订单`
              },
              (err) => {}
            )
          }
        })
      } else {
        params = { ...this.postData }
        params.type = 'ALL'
        this.loading = true
        serveList(
          params,
          (res) => {
            _this.loading = false
            _this.formLimit.visible = true
            _this.formLimit.value = `您本次选择了${res.total}条订单`
          },
          (err) => {}
        )
      }
    },
    getPush(val) {
      this.pushCheck = val
    },
    getDX(val) {
      this.dxCheck = val
    },
    smsCheckedChange(val) {
      if (val) {
        this.$refs['smsForm'].validate((res) => {})
        switch (this.serviceForm.configData.userType) {
          case 'CONSULTANT':
            this.$refs['dingtalkForm'].validateField('dingtalk', (errMsg) => {})
            break
          case 'STUDENT':
            this.$refs['noticeForm'].validateField('notice', (errMsg) => {})
            this.$refs['pushForm'].validateField('push', (errMsg) => {})
            this.$refs['playscreenForm'].validateField(
              'playscreen',
              (errMsg) => {}
            )
            break
          default:
            break
        }
      } else {
        this.$refs['smsForm'].resetFields()
      }
    },
    dingCheckedChange(val) {
      if (val) {
        this.$refs['dingtalkForm'].validate((res) => {})
        this.$refs['smsForm'].validateField('sms', (errMsg) => {})
      } else {
        this.$refs['dingtalkForm'].resetFields()
      }
    },

    noticeCheckedChange(val) {
      if (val) {
        this.$refs['noticeForm'].validate((res) => {})
        this.$refs['smsForm'].validateField('sms', (errMsg) => {})
        this.$refs['pushForm'].validateField('push', (errMsg) => {})
        this.$refs['playscreenForm'].validateField('playscreen', (errMsg) => {})
      } else {
        this.$refs['noticeForm'].resetFields()
      }
    },
    pushCheckedChange(val) {
      if (val) {
        this.$refs['pushForm'].validate((res) => {})
        this.$refs['smsForm'].validateField('sms', (errMsg) => {})
        this.$refs['noticeForm'].validateField('notice', (errMsg) => {})
        this.$refs['playscreenForm'].validateField('playscreen', (errMsg) => {})
      } else {
        this.$refs['pushForm'].resetFields()
      }
    },
    playscreenCheckedChange(val) {
      if (val) {
        this.$refs['playscreenForm'].validate((res) => {})
        this.$refs['noticeForm'].validateField('notice', (errMsg) => {})
        this.$refs['smsForm'].validateField('sms', (errMsg) => {})
        this.$refs['pushForm'].validateField('push', (errMsg) => {})
      } else {
        this.channelsList.playscreen.bombScreenImage = ''
        this.$refs['playscreenForm'].resetFields()
      }
    },
    handleDateChange(val) {
      if (val) {
        this.serviceForm.configData.startTime = val[0]
        this.serviceForm.configData.endTime = val[1]
      } else {
        this.serviceForm.configData.startTime = ''
        this.serviceForm.configData.endTime = ''
      }
    },
    // 选择渠道对象转换为传参数组
    channelsListToMessageChannels() {
      let messageChannels = []
      if (this.smsChecked) {
        messageChannels.push(this.channelsList.sms)
      }
      switch (this.serviceForm.configData.userType) {
        // 通知用户类型=>顾问
        case 'CONSULTANT':
          if (this.dingtalkChecked) {
            messageChannels.push(this.channelsList.dingtalk)
          }
          break
        // 通知用户类型=>学员
        case 'STUDENT':
          if (this.noticeChecked) {
            messageChannels.push(this.channelsList.notice)
          }
          if (this.pushChecked) {
            messageChannels.push(this.channelsList.push)
          }
          if (this.playscreenChecked) {
            messageChannels.push(this.channelsList.playscreen)
          }
          break
        default:
          break
      }
      this.serviceForm.messageChannels = messageChannels
    },
    // 选择渠道数组转换为选择渠道对象
    messageChannelsToChannelsList() {
      this.serviceForm.messageChannels.forEach((item) => {
        // PUSH,NOTICE,SMS,DINGTALK,BOMB_SCREEN
        switch (item.type) {
          case 'SMS':
            this.smsChecked = true
            this.channelsList.sms = item
            break
          case 'DINGTALK':
            this.dingtalkChecked = true
            this.channelsList.dingtalk = item
            break
          case 'NOTICE':
            this.noticeChecked = true
            this.channelsList.notice = item
            break
          case 'PUSH':
            this.pushChecked = true
            this.channelsList.push = item
            break
          case 'BOMB_SCREEN':
            this.playscreenChecked = true
            this.channelsList.playscreen = item
            break
          default:
            break
        }
      })
    },
    // 到期时间转换
    dueDateToserviceTime(startTime, endTime) {
      if (startTime && endTime) {
        this.serviceTime.push(startTime)
        this.serviceTime.push(endTime)
      }
    },
    //封面图设置
    getImgUrl(url) {
      this.channelsList.playscreen.bombScreenImage = url
      this.$refs['playscreenForm'].validateField(
        'bombScreenImage',
        (errMsg) => {}
      )
    }
  }
}
</script>

<style lang="less" scoped>
:deep(.el-form-item__label) {
  color: #333333 !important;
  font-weight: 400;
}
:deep(.el-form-item__label) {
  display: flex !important;
  justify-content: flex-start !important;
}
:deep(.el-form-item__label) {
  color: #333333 !important;
  font-weight: 400;
}
:deep(.el-form-item__error) {
  margin-left: 100px;
}
:deep(.el-form-item__content) {
  margin-left: 200px;
}
.col_title {
  color: rgb(51, 51, 51);
  font-size: 20px;
  font-weight: 700;
}
.col {
  display: flex !important;
  flex-direction: column !important;
}
.col_title {
  color: rgb(51, 51, 51);
  font-size: 20px;
  font-weight: 700;
}
.row_center {
  display: flex;
  justify-content: center;
  align-items: center;
}
.temp-container {
  display: grid;
  grid-template-columns: repeat(100%);
  .table {
    width: 500px;
    height: 100px;
    td th {
      text-align: center;
    }
  }
}
.form-box {
  display: flex;
  margin-left: 100px;
}
.notice-wrap {
  margin-left: 100px;
  .notice-btn {
    color: #03be91;
    cursor: pointer;
    margin-left: 20px;
  }
}
.playscreen-wrap {
  margin-left: 100px;
}

.serviceTime {
  margin-left: 100px;
}
.channel-wrap {
  margin-left: 90px;
  & > p {
    margin: 0 0 0 10px;
    color: red;
  }
  .channel-checkbox {
    margin-left: 10px;
  }
}
.channel-content {
  margin-left: 100px;
  .content-tip {
    width: 120px;
    text-align: left;
    display: inline-block;
  }
}
.link-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-left: 100px;
  .short-link {
    margin-right: 30px;
  }
  .short-link-btn {
    width: 100px;
    height: 30px;
    margin-left: 20px;
    background: rgba(29, 200, 164, 1);
    color: white;
    cursor: pointer;
  }
}
.push-content {
  // margin-left: 100px;
  // display: flex;
  // & > span {
  //   margin-right: 30px;
  // }
  // .push-content_input {
  //   // width: 50%;
  //   flex: 1;
  //   margin-left: 20px;
  // }
}
.view-order_btn {
  color: #03be91;
  margin-left: 100px;
  cursor: pointer;
}
.position_top {
  position: relative !important;
  top: -10px !important;
}
.row_around {
  display: flex !important;
  align-items: center !important;
  justify-content: space-around !important;
}
</style>
